from logger import log
from database import Database
import os
import json
import math

class Storage:
	class __impl:
		def __init__(self):
			self.idCounter = 1000
			self.database = Database()
			self.conf = {}
			for item in os.listdir('./conf'):
				if item[0] == '.':
					continue
				name = item.split('.')[0]
				log('Loading configuration `%s`'%name)
				self.conf[name] = self.getJSON('./conf/%s'%item)
			log('Created Storage')

		def getFile(self, path):
			f = file(path, 'r')
			data = f.read()
			f.close()
			return data

		def getJSON(self, path):
			return json.loads(self.getFile(path))

		def newId(self):
			self.idCounter = self.idCounter + 1
			return self.idCounter

		def get(self, conf, name):
			if name in self.conf[conf].keys():
				return self.conf[conf][name]
			else:
				log('WARNING: Requested unexisting property %s->%s'%(conf,name))

		def dist(self, o1, o2):
			return math.sqrt((o1['x'] - o2['x'])**2 + (o1['y'] - o2['y'])**2)

	__instance = None

	def __init__(self):
		if Storage.__instance is None:
			Storage.__instance = Storage.__impl()

		self.__dict__['_Storage__instance'] = Storage.__instance

	def __getattr__(self, attr):
		return getattr(self.__instance, attr)

	def __setattr__(self, attr, value):
		return setattr(self.__instance, attr, value)
